package models

import (
	"errors"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cast"
	"hc_server/routers/response/salesmenResponse"
)

// Salesmen 业务员表
type Salesmen struct {
	Model
	Name          string `json:"name" gorm:"comment:'业务员姓名'"`
	Mobile        string `json:"mobile" gorm:"comment:'业务员手机号码'"`
	AgentId       string `json:"agent_id" gorm:"comment:'代理商id'"`
	AgentRelation string `json:"agent_relation" gorm:"comment:'代理商关系'"`
}

// SalesmenExistByID 通过id判断是否存在
func SalesmenExistByID(id int) error {
	var salesmen Salesmen
	db.Select("id").Where("id = ?", id).First(&salesmen)
	if salesmen.ID > 0 {
		return nil
	}
	return errors.New("此业务员不存在")
}

// SalesmenExistByMobile 通过mobile判断是否存在
func SalesmenExistByMobile(mobile string) error {
	var salesmen Salesmen
	db.Select("id").Where("mobile = ?", mobile).First(&salesmen)
	if salesmen.ID > 0 {
		return nil
	}
	return errors.New("此业务员不存在")
}

// SalesmenRegister 注册业务员
func SalesmenRegister(sales Salesmen) error {
	err := db.Create(&sales).Error
	if err != nil {
		logrus.WithError(err).Infof("业务员注册失败: sales:%v", sales)
		return errors.New("注册业务员错误")
	}

	return nil
}

// SalesmenMerchantSalesmenList 商户入驻获取业务员列表
func SalesmenMerchantSalesmenList(id, pageNum, pageSize interface{}, keyword string) (map[string]interface{}, error) {
	var (
		result = make([]*salesmenResponse.TeamManagerSalesmenListResponse, 0)
		count  int64
		sql    = ""
	)

	if len(keyword) > 0 {
		sql = fmt.Sprintf("agent_id = %d AND name LIKE '%s%%'", id, keyword)
	} else {
		sql = fmt.Sprintf("agent_id = %d", id)
	}

	db.Model(&Salesmen{}).
		Where(sql).
		Limit(cast.ToInt(pageSize)).
		Offset((cast.ToInt(pageNum) - 1) * cast.ToInt(pageSize)).
		Order("created_at DESC").
		Scan(&result)

	db.Model(&Salesmen{}).
		Where(sql).
		Count(&count)

	return map[string]interface{}{
		"result": result,
		"count":  count,
	}, nil
}

// TeamMerchantSalesmenList 团队管理获取业务员列表
func TeamMerchantSalesmenList(id, pageNum, pageSize interface{}) (map[string]interface{}, error) {
	var (
		result = make([]*salesmenResponse.TeamManagerSalesmenListResponse, 0)
		count  int64
	)

	db.Model(&Salesmen{}).
		Where("agent_id = ?", id).
		Limit(cast.ToInt(pageSize)).
		Offset((cast.ToInt(pageNum) - 1) * cast.ToInt(pageSize)).
		Order("created_at DESC").
		Scan(&result)

	db.Model(&Salesmen{}).
		Where("agent_id = ?", id).
		Count(&count)

	return map[string]interface{}{
		"result": result,
		"count":  count,
	}, nil
}

// GetAgentSalesmenCount 获取代理商下业务员数量
//func GetAgentSalesmenCount(agentId int) int64 {
//	var count int64
//	db.Model(&Agent{}).Select("COUNT(agents.id)").
//		Joins("LEFT JOIN salesmens ON FIND_IN_SET(agents.agent_relation,salesmens.agent_relation)").Where("agents.id = ?", agentId).Count(&count)
//	return count
//}
